﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using ZeroSum.Plugin.Authentication.JwtBearer.Authentication;
using ZeroSum.Plugin.Authentication.JwtBearer.Authorization;

namespace ZeroSum.Plugin.Authentication.JwtBearer;

public static class JwtExtensions
{
    /// <summary>
    ///     添加JWT
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddJwtBear(this IServiceCollection services)
    {
        services.AddJwtBearer();
        services.AddAuthorization(opts =>
        {
            opts.AddPolicy(ZeroSumPermissionRequirement.Policy,
                policy => { policy.Requirements.Add(new ZeroSumPermissionRequirement()); });
        });
        return services;
    }

    private static IServiceCollection AddJwtBearer(this IServiceCollection services)
    {
        const string defaultSchema = JwtBearerDefaults.AuthenticationScheme;
        var builder = services.AddAuthentication(opts => { opts.DefaultScheme = defaultSchema; });
        var jwtBearerService =
            (IJwtBearerService) services.BuildServiceProvider().GetService(typeof(IJwtBearerService));
        builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,
            opts => { opts.TokenValidationParameters = jwtBearerService.CreateTokenValidationParameters(); });

        return services;
    }
}